<template>
  <div class="SMS-management">
    <div class="search">
      <el-form ref="searchData" :inline="true" :model="searchData" class="demo-form-inline clearfix">
        <el-form-item label="收件人" prop="Recipient">
          <el-input
            placeholder="请输入用户名"
            v-model.trim="searchData.Recipient"
            @keyup.enter.native="search"
            size="small"
            @input="aearchInput"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="收件号码" prop="ReceiveNumber">
          <el-input
            placeholder="输入收件号码"
            v-model.trim="searchData.ReceiveNumber"
            size="small"
            @keyup.enter.native="search"
            @input="aearchInput"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item size="small" label="发送状态" prop="isSuccess">
          <el-select v-model="searchData.isSuccess" placeholder="请选择发送状态">
            <el-option label="发送成功" value="1"></el-option>
            <el-option label="发送失败" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item size="small" label="预约起止时间" prop="searchTime">
          <el-date-picker
            size="small"
            v-model="searchData.searchTime"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="search">搜索</el-button>
          <el-button type="info" size="small" @click="resetSearch('searchData')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="modify">
      <!-- <el-button type="primary" size="small" icon="el-icon-s-tools" @click="$router.push('SMSTemplate')">模板管理</el-button> -->
      <el-button
        type="primary"
        size="small"
        icon="el-icon-delete"
        @click="deleteHandle"
        :disabled="isDisable"
      >批量删除</el-button>
      <el-button
        type="primary"
        size="small"
        icon="el-icon-delete"
        @click="sendteHandle"
        :disabled="isDisable"
      >批量发送</el-button>
    </div>

    <!-- 表格内容 -->
    <el-tabs type="border-card" v-model="type" @tab-click="SMSContent">
      <el-tab-pane name="0" label="线下预约">
        <el-table
          :data="tableData"
          style="width: 100%"
          @selection-change="selectChange"
          ref="table"
          v-loading="loading"
          element-loading-text="加载中"
        >
          <el-table-column align="center" type="selection" width="55"></el-table-column>
          <el-table-column align="center" type="index" label="序号" width="60"></el-table-column>
          <el-table-column align="center" prop="name" label="收件人" width="150"></el-table-column>
          <el-table-column align="center" prop="phone" label="收件号码" width="200"></el-table-column>
          <el-table-column align="center" prop="orderDate" label="预约时间"></el-table-column>
          <el-table-column align="center" prop="formIsOnLine" label="短信类型"></el-table-column>
          <el-table-column align="center" prop="status" label="发送状态" width="80px">
            <template v-slot="scope">
              <el-tag type="success" v-if="scope.row.isSuccess % 2 !== 0">发送成功</el-tag>
              <el-tag type="danger" v-else>发送失败</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300">
            <template v-slot="scope">
              <div class="duanxin">
                <el-link
                  type="primary"
                  icon="el-icon-refresh-right"
                  size="small"
                  @click="reSend(scope.row)"
                >重发</el-link>
                <el-link
                  type="primary"
                  @click="rePhoneModol(scope.row)"
                  icon="el-icon-edit"
                  size="small"
                >修改电话号码</el-link>
                <el-link
                  type="danger"
                  @click="deleteSMS(scope.row)"
                  icon="el-icon-delete"
                  size="small"
                >删除</el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane name="1" label="线上预约">
        <el-table
          :data="tableData"
          style="width: 100%"
          @row-click="rowClickHandle"
          @selection-change="selectChange"
          ref="table"
          v-loading="loading"
          element-loading-text="加载中"
        >
          <el-table-column align="center" type="selection" width="55"></el-table-column>
          <el-table-column align="center" type="index" label="序号" width="60"></el-table-column>
          <el-table-column align="center" prop="name" label="收件人" width="150"></el-table-column>
          <el-table-column align="center" prop="phone" label="收件号码" width="200"></el-table-column>
          <el-table-column align="center" prop="orderDate" label="预约时间"></el-table-column>
          <el-table-column align="center" prop="formIsOnLine" label="短信类型"></el-table-column>
          <el-table-column align="center" prop="status" label="发送状态" width="80px">
            <template v-slot="scope">
              <el-tag type="success" v-if="scope.row.isSuccess % 2 !== 0">发送成功</el-tag>
              <el-tag type="danger" v-else>发送失败</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300">
            <template v-slot="scope">
              <div class="duanxin">
                <el-link
                  type="primary"
                  icon="el-icon-refresh-right"
                  size="small"
                  @click="reSend(scope.row)"
                >重发</el-link>
                <el-link
                  type="primary"
                  @click="rePhoneModol(scope.row)"
                  icon="el-icon-edit"
                  size="small"
                >修改电话号码</el-link>
                <el-link
                  type="danger"
                  @click="deleteSMS(scope.row)"
                  icon="el-icon-delete"
                  size="small"
                >删除</el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane name="2" label="证书发放">
        <el-table
          :data="tableData"
          style="width: 100%"
          @row-click="rowClickHandle"
          @selection-change="selectChange"
          ref="table"
          v-loading="loading"
          element-loading-text="加载中"
        >
          <el-table-column align="center" type="selection" width="55"></el-table-column>
          <el-table-column align="center" type="index" label="序号" width="60"></el-table-column>
          <el-table-column align="center" prop="name" label="收件人" width="150"></el-table-column>
          <el-table-column align="center" prop="phone" label="收件号码" width="200"></el-table-column>
          <el-table-column align="center" prop="orderDate" label="预约时间"></el-table-column>
          <el-table-column align="center" prop="formIsOnLine" label="短信类型"></el-table-column>
          <el-table-column align="center" prop="status" label="发送状态" width="80px">
            <template v-slot="scope">
              <el-tag type="success" v-if="scope.row.isSuccess % 2 !== 0">发送成功</el-tag>
              <el-tag type="danger" v-else>发送失败</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300">
            <template v-slot="scope">
              <div class="duanxin">
                <el-link
                  type="primary"
                  icon="el-icon-refresh-right"
                  size="small"
                  @click="reSend(scope.row)"
                >重发</el-link>
                <el-link
                  type="primary"
                  @click="rePhoneModol(scope.row)"
                  icon="el-icon-edit"
                  size="small"
                >修改电话号码</el-link>
                <el-link
                  type="danger"
                  @click="deleteSMS(scope.row)"
                  icon="el-icon-delete"
                  size="small"
                >删除</el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 修改电话号码 -->
 <!-- :closeOnClickModal="false" -->
      <el-dialog  title="修改电话号码" :visible.sync="rePhoneVisible" width="30%">
        <el-form :model="reModol" ref="form" :rules="addbatchrules" label-width="100px">
          <el-form-item label="收件人">
            <el-input class="sjr" disabled v-model="reModol.name"></el-input>
          </el-form-item>
          <el-form-item  label="预约时间">
            <el-input disabled v-model="reModol.orderDate"></el-input>
          </el-form-item>
          <el-form-item  label="短信类型">
            <el-input disabled v-model="reModol.formIsOnLine"></el-input>
          </el-form-item>
          <el-form-item  label="电话号码" prop="phone">
            <el-input v-model="reModol.phone"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancleChange">取 消</el-button>
          <el-button type="primary" @click="rePhone()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页 -->
      <div class="block clearfix">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-tabs>
  </div>
</template>
<script>
import qs from "../utils/qs";
import timeScope from "../components/wDate";
export default {
  data() {
    return {
      // 记录电话号码
      oldPhone: '',
      // 加载动效
      loading: false,
      // 表格数据
      tableData: [],
      // 选中的模板
      checkedTemplat: [],
      //查询预约方式
      // isOnLine: "",
      type: 0,
      //表单预约方式
      formIsOnLine: "",
      // 收件内容
      // ReceiveCotent: "",
      //预约时间
      orderDate: "",
      valNum: 1,
      startTime: "", // 开始时间
      endTime: "", // 结束时间
      //分页
      //第几页
      pageSize: 5,
      pageNum: 1,
      pagelength: 0,
      addbatchrules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            // pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
            pattern: /^1[34578]\d{9}$/,
            message: "请输入正确的手机号码",
          },
        ],
      },
      //搜索数据
      operation: {
        name: "",
        isActivate: true,
      },

      // 数据总条目数
      total: 1,
      // 搜索
      searchData: {
        // 收件人
        Recipient: "",
        // 收件号码
        ReceiveNumber: "",
        //发送状态查询
        isSuccess: "",
        //搜索时间
        searchTime: "",
      },

      //弹框
      rePhoneVisible: false,
      //弹框内容
      reModol: "",

      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  components: {
    timeScope,
  },
  methods: {
    // 取消电话号码修改
    cancleChange(){
      this.rePhoneVisible = false;
      this.reModol.phone = this.oldPhone;
    },

    //tab栏切换
    SMSContent() {
      this.search();
    },
    // // 显示数量切换
    // handleSizeChange(num) {
    //   this.pageSize = num;
    //   this.requestData();
    // },
    // 请求数据
    requestData(page = this.pageNum) {
      let data = this.isSearchData().params;
      this.loading = true;
      // , {
      //   params: { pageNum: page, pageSize: num },
      // }
      this.$http("/trademark/SMSList/findBy", {
        params: data,
      })
        .then(
          ({ data: response }) => {
            this.loading = false;
            if (response.code !== 200) {
              return this.$message.error("数据获取失败");
            } else {
              this.tableData = response.data.list;
              this.pageNum = response.data.pageNum;
              this.total = response.data.total;
              this.totalPage = response.data.totalPage;
              this.searchData.isSuccess = response.data.isSuccess;
              //对象中添加 formIsOnLine 预约方式
              this.tableData.forEach((item) => {
                if (item.type == 0) {
                  item.formIsOnLine = "线下预约";
                } else if (item.type == 1) {
                  item.formIsOnLine = "线上预约";
                } else if (item.type == 2) {
                  item.formIsOnLine = "证书发放";
                }
              });
            }
          },
          (err) => err
        )
        .finally(() => (this.loading = false));
    },
    // 通过id删除数据
    requestDelete(ID) {
      this.loading = true;
      this.$http
        .post("/trademark/SMSList/batchDelete", JSON.stringify([ID]))
        .then(
          ({ data: response }) => {
            if (response.code !== 200) return this.$message.error("删除失败");
            this.requestData();
            this.$message.success("删除成功");
          },
          (err) => err
        )
        .finally(() => (this.loading = false));
    },
    //通过收件人，收件号码，收件内容查询并分页
    queryInfo(key, val) {
      this.loading = true;
      this.$http(`/trademark/SMSList/findByType?${key}=${val}`)
        .then(
          ({ data: response }) => {
            if (response.code !== 200) return this.$message.error("查询失败");
            this.tableData = response.data.list;
          },
          (err) => err
        )
        .finally(() => (this.loading = false));
    },
    // 重新发送
    reSend(row) {
      var data = new FormData();
      data.append("id", row.id);
      this.$http.post("/trademark/SMSList/reSendMsg", data).then(
        ({ data: response }) => {
          if (response.code !== 200) {
            this.rePhoneVisible = false;
            return this.$message.error("发送失败");
          } else {
            this.requestData();
            this.rePhoneVisible = false;
            this.$message.success("发送成功");
          }
        },
        (err) => err
      );
    },
    //修改电话号码按钮
    rePhoneModol(row) {

      this.oldPhone = row.phone;
      this.reModol = row;
      this.rePhoneVisible = true;
    },
    //修改电话号码
    rePhone() {
      var data = new FormData();
      data.append("id", this.reModol.id);
      data.append("phone", this.reModol.phone);
      this.$http.post("/trademark/SMSList/modifyPhoneById", data).then(
        ({ data: response }) => {
          if (response.code !== 200) {
            this.rePhoneVisible = false;
            this.reModol.phone = this.oldPhone;
            this.requestData();
            return this.$message.error("修改失败");
          } else {
            this.rePhoneVisible = false;
            this.requestData();
            this.$message.success("修改成功");
          }
        },
        (err) => err
      );
    },
    // 单项删除
    deleteSMS({ id }) {
      var confirm = this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((re) => {
          this.requestDelete(id);
        })
        .catch((cancle) => cancle);
    },
    // 选中行
    rowClickHandle(row, column, event) {
      const target = event.target;
      if (
        target.nodeName === "BUTTON" ||
        target.parentElement.nodeName === "BUTTON"
      )
        return;
      this.$refs.table.toggleRowSelection(
        this.tableData.filter((val) => val.id === row.id)[0]
      );
    },
    // 多项删除请求
    requestDeletes(arr) {
      this.loading = true;
      this.$http
        .post("/trademark/SMSList/batchDelete", JSON.stringify(arr))
        .then(
          ({ data: response }) => {
            if (response.code !== 200) return this.$message.error("删除失败");
            this.requestData();
            this.$message.success("删除成功");
          },
          (err) => err
        )
        .finally(() => (this.loading = false));
    },
    // 多项删除
    deleteHandle() {
      var confirm = this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((re) => {
          var arr = this.checkedTemplat.map((val) => val.id);
          this.requestDeletes(arr);
        })
        .catch((cancle) => cancle);
    },
    // 批量发送
    requestSends(arr) {
      this.loading = true;
      this.$http
        .post("/trademark/SMSList/reSendMsgByIds", JSON.stringify(arr))
        .then(
          ({ data: response }) => {
            if (response.code !== 200) return this.$message.error("操作失败");
            this.requestData();
            this.$message.success(response.message);
          },
          (err) => err
        )
        .finally(() => (this.loading = false));
    },
    //批量发送
    sendteHandle() {
      var confirm = this.$confirm("此操作将批量发送短信, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((re) => {
          var arr = this.checkedTemplat.map((val) => val.id);
          this.requestSends(arr);
        })
        .catch((cancle) => cancle);
    },
    // 选中事件
    selectChange(selection) {
      this.checkedTemplat = selection;
    },
    dateTime(time) {
      // let year = new Date(time).getFullYear();
      // let month = new Date(time).getMonth() + 1;
      // let day = new Date(time).getDate();
      // month < 10 ? (month = "0" + month) : month;
      // day < 10 ? (day = "0" + day) : day;
      // let tim = year + "-" + month + "-" + day;
      let times = [];
      for (let i = 0; i < 2; i++) {
        let year = new Date(time[i]).getFullYear();
        let month = new Date(time[i]).getMonth() + 1;
        let day = new Date(time[i]).getDate();
        month < 10 ? (month = "0" + month) : month;
        day < 10 ? (day = "0" + day) : day;
        let tim = year + "-" + month + "-" + day;
        times.push(tim)
      }
      return times;
    },
    //搜索数据
    isSearchData() {
      let startT;
      let endT;
      if (this.searchData.searchTime) {
        startT = this.dateTime(
          (this.startT = this.dateTime(this.searchData.searchTime))
        )[0];
        endT = this.dateTime((this.startT = this.dateTime(this.searchData.searchTime)))[1];
      }
      return {
        params: {
          name: this.searchData.Recipient,
          phone: this.searchData.ReceiveNumber,
          type: this.type,
          isSuccess: this.searchData.isSuccess,
          startOrderDate: startT,
          endOrderDate: endT,
          pageSize: this.pageSize,
          pageNum: this.pageNum,
        },
      };
    },
    // 搜索
    search(option) {
      //处理日期格式
      // let isStartTime = +new Date(startT);
      // let isendTime = +new Date(endT);
      let data = this.isSearchData().params;
      //发送请求
      this.$http("/trademark/SMSList/findBy", {
        params: data,
      })
        .then(
          ({ data: response }) => {
            if (response.code !== 200) {
              return this.$message.error("查询失败");
            } else {
              this.tableData = response.data.list;
              this.pageNum = response.data.pageNum;
              this.total = response.data.total;
              this.totalPage = response.data.totalPage;
              this.tableData.forEach((item) => {
                if (item.type == 0) {
                  item.formIsOnLine = "线下预约";
                } else if (item.type == 1) {
                  item.formIsOnLine = "线上预约";
                } else if (item.type == 2) {
                  item.formIsOnLine = "证书发放";
                }
              });
            }
          },
          (err) => err
        )
        .finally(() => (this.loading = false));
    },
    storeTime(startTime, endTime) {
      this.startTime = startTime;
      this.endTime = endTime;
    },
    //重置
    resetSearch(searchData) {
      this.$refs[searchData].resetFields();
    },
    // 取消搜索
    cancleSearch() {
      this.ReceiveCotent = "";
      this.searchData.ReceiveNumber = "";
      this.searchData.Recipient = "";
      this.requestData();
    },
    // 查询内容改变
    aearchInput() {
      // this.onSearch || this.requestData();
    },
    //分页
    handleSizeChange(val) {
      this.pageSize = val;
      if (this.operation.isActivate) {
        this.paging();
      } else {
        this.apisearch();
      }
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      if (this.operation.isActivate) {
        this.paging();
      } else {
        this.apisearch();
      }
    },
    //请求接口
    //分页请求
    paging() {
      let data = this.isSearchData().params;
      this.$http
        .get("trademark/SMSList/findBy", {
          params: data,
        })
        .then((res) => {
          this.tableData = res.data.data.list;
          this.tableData.forEach((item) => {
            if (item.type == 0) {
              item.formIsOnLine = "线下预约";
            } else if (item.type == 1) {
              item.formIsOnLine = "线上预约";
            } else if (item.type == 2) {
              item.formIsOnLine = "证书发放";
            }
          });
          this.pagelength = res.data.data.total;
          if (res.status !== 200) {
            return this.$message.error("获取数据失败");
          }
        });
    },
  },
  computed: {
    // 是否处于搜索状态
    onSearch() {
      return (
        !!this.ReceiveCotent ||
        !!this.searchData.ReceiveNumber ||
        !!this.searchData.Recipient
      );
    },
    // 删除按钮禁用状态
    isDisable() {
      return !this.checkedTemplat.length;
    },
  },
  created() {
    this.requestData();
  },
};
</script>
<style lang="less" scoped>
.SMS-management {
  .search {
    .demo-form-inline {
      display: flex;
      flex-wrap: wrap;
    }
  }
  .modify {
    margin: 20px 0;
  }
}
.duanxin > a {
  margin-left: 20px;
}
.line {
  text-align: center;
}
.el-form-item {
  display: flex;
  justify-content: start;
  padding: 0;
}
.el-button + .el-button {
  margin-left: 15px;
}
.clearfix::after {
  content: "";
  display: none;
  clear: both;
}
</style>
<style>
.SMS-management .el-form-item__content {
  margin: 0 !important;
}
.SMS-management .el-date-editor--daterange{
  width: 250px!important;
}
</style>
